package com.yhy.manager.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yhy.dubbo.api.UserInfoApi;
import com.yhy.manager.domain.Analysis;
import com.yhy.manager.domain.AnalysisByDay;
import com.yhy.manager.domain.AnalysisUser;
import com.yhy.manager.domain.Years;
import com.yhy.manager.mapper.AnalysisByDayMapper;
import com.yhy.manager.mapper.LogMapper;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DashboardService {

    @Autowired
    private LogMapper logMapper;


    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    @Reference
    private UserInfoApi userInfoApi;

    public ResponseEntity summary() {
//        1.首先确定今天的日期
        Date today = new Date();
        String todayStr = new SimpleDateFormat("yyyy-MM-dd").format(today);
        //2准备参数封装Analysis
        //2.1 累计用户
        Integer cumulativeUsers = userInfoApi.count();
        //2.2 过去30天活跃用户
        DateTime lastMonth = DateUtil.offsetMonth(today, -1);
        Integer activePassMonth = analysisByDayMapper.queryActivePassMonth(lastMonth.toString());
        //2.3 过去7天活跃用户
        DateTime lastWeek = DateUtil.offsetWeek(today, -1);
        Integer activePassWeek = analysisByDayMapper.queryActivePassWeek(lastWeek.toString());
        //2.4 新增用户(今日)
        //查出今日分析对象
        QueryWrapper qw = new QueryWrapper();
        qw.eq("record_date",todayStr);
        AnalysisByDay todayAnalysis = analysisByDayMapper.selectOne(qw);
        Integer newUsersToday = todayAnalysis.getNumRegistered();
        //准备好昨日日期 准备对比
        DateTime yesterday = DateUtil.yesterday();
        String yesterdayStr = new SimpleDateFormat("yyyy-MM-dd").format(yesterday);
        QueryWrapper qw1 = new QueryWrapper<>();
        qw1.eq("record_date",yesterdayStr);
        AnalysisByDay yesterdayAnalysis = analysisByDayMapper.selectOne(qw1);
        //2.5 今日新增用户涨跌率
        Integer newUsersYesterday = yesterdayAnalysis.getNumRegistered();
        Integer newUsersTodayRate = newUsersToday-newUsersYesterday;
            newUsersTodayRate = (int) ((new BigDecimal((float) newUsersTodayRate / newUsersYesterday).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())*100);

        //2.6 登录次数(今日)
        Integer loginTimesToday = todayAnalysis.getNumLogin();
        //2.7 今日登录次数涨跌率
        Integer loginTimesYesterday = yesterdayAnalysis.getNumLogin();
        Integer loginTimesTodayRate = loginTimesToday-loginTimesYesterday;
            loginTimesTodayRate = (int) ((new BigDecimal((float) loginTimesTodayRate / loginTimesYesterday).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())*100);

        //2.8 活跃用户(今日)
        Integer activeUsersToday = todayAnalysis.getNumActive();
        //2.9 今日活跃用户涨跌率
        Integer activeUsersYesterday = yesterdayAnalysis.getNumActive();
        Integer activeUsersTodayRate =activeUsersToday-activeUsersYesterday;

        activeUsersTodayRate =   (int) ((new BigDecimal((float) activeUsersTodayRate / activeUsersYesterday).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())*100);

        //封装
        Analysis analysis = new Analysis();
        analysis.setCumulativeUsers(cumulativeUsers);
        analysis.setActivePassMonth(activePassMonth);
        analysis.setActivePassWeek(activePassWeek);
        analysis.setNewUsersToday(newUsersToday);
        analysis.setNewUsersTodayRate(newUsersTodayRate);
        analysis.setLoginTimesToday(loginTimesToday);
        analysis.setLoginTimesTodayRate(loginTimesTodayRate);
        analysis.setActiveUsersToday(activeUsersToday);
        analysis.setActiveUsersTodayRate(activeUsersTodayRate);
        //构造返回值Json
        String json = JSON.toJSONString(analysis);
        return ResponseEntity.ok(json);
    }

    public ResponseEntity users(Long sd, Long ed, Integer type) {
        DateTime startDate = DateUtil.date(sd);
        DateTime endDate = DateUtil.date(ed);
        String startYear = DateUtil.format(startDate, "yyyy");
        String endYear = DateUtil.format(endDate, "yyyy");
        AnalysisUser analysisUser = new AnalysisUser();
        analysisUser.setThisYear(new ArrayList<>());
        analysisUser.setLastYear(new ArrayList<>());
        String typeStr = type == 101?"num_registered":type==102?"num_active":"num_retention1d";
//        typeStr = "IFNULL(SUM("+typeStr+"),0)";
//        typeStr = "SUM("+typeStr+")";
        String likeStr = "LIKE ";
        for (int i = 1; i <= 12; i++) {
            if(i<10){
//                String month = "0"+i;
//                QueryWrapper<AnalysisUser> qw = new QueryWrapper();
//                qw.like("record_date",startYear+"-"+month).select("SUM(num_registered) AS total");
////                Long startAmount = analysisByDayMapper.query101ByMonth(qw);
//                List list = analysisByDayMapper.selectList(qw);
//                for (Object o : list) {
//                    System.out.println("TEST====="+o+"");
//                }
//                analysisUser.getThisYear().add(new Years(month,startAmount));
//                Long startAmount = analysisByDayMapper.queryByMonthAndType(likeStr+startYear+"-"+month+"%",typeStr);
//                analysisUser.getThisYear().add(new Years(month,startAmount));
//                Long endAmount = analysisByDayMapper.queryByMonthAndType(likeStr+endYear+"-"+month+"%",typeStr);
//                analysisUser.getLastYear().add(new Years(month,endAmount));
            }else{
                Long startAmount = analysisByDayMapper.queryByMonthAndType(startYear+"-"+i+"%",typeStr);
                analysisUser.getThisYear().add(new Years(i+"",startAmount));
                Long endAmount = analysisByDayMapper.queryByMonthAndType(endYear+"-"+i+"%",typeStr);
                analysisUser.getLastYear().add(new Years(i+"",endAmount));
            }
        }
        //构造返回
        String json = JSON.toJSONString(analysisUser);
        System.out.println(json);
        return ResponseEntity.ok(json);
    }
}
